<?php
   set_time_limit(0);

   $dir = '/var/music/';
   $incomingDir = $dir . 'INCOMING/';
   $outgoingDir = $dir . 'UNSORTED/';
   
   include_once('./includes/getid3/getid3/getid3.php');

//the loadTrkFileInfo() function inputs two strings, full string paths 
//to the incoming directory (where scanned files are) and outgoing directory (where they will be moved to).
//
//this function scans all the files in a directory and loads them into a 3-part array:
// 0. tracks that already exist in the DB
// 1. albums that already exist in the DB, but tracks that do not.
// 2. no track or album of this description seems to be in the DB 
function loadTrkFileInfo ($incomingDir = '/var/music/INCOMING/', $outgoingDir = '/var/music/UNSORTED/') {
//   $filearr = array();
   $i = 0; // iterator for scanned files
   $j = 0; // iterator for files that will be added to an existing album 
   $k = 0; // iterator for DB entries where the file already exists 
   $l = 0; // iterator for brand new tracks with no files or DB entries 
   
   // this array contains filetypes we consider valid
   $fileTypes = array('mp3','ogg','wmv','asf','flac','wma','wav'); // for now, m4a doesn't seem to work... 
   
   // instantiate new object for getid3...burrito
   $getID3 = new getID3;
   if ($handle = opendir($incomingDir)) {
      // search through the directory 
      while (false !== ($file = readdir($handle))) {
         // if a the file appears as "." or "..", it's a directory and we'll get infinite loops, so screen them out
         if ($file != '.' && $file != '..' && !is_dir($incomingDir.$file)) {
	 
            // look for the file in accepted filetypes array
            $ext = strtolower(array_pop(explode(".",$file)));
            if(in_array($ext,$fileTypes)) {
//               $fileSize = filesize($incomingDir.$file);

               // use getid3's analyze function to examine the incoming file 
               $trackInfo = $getID3->analyze($incomingDir.$file);
               
               // getid3's CopyTagsToComments function can take the snagged metadata and put it into an array marked as 'comments_html'
               getid3_lib::CopyTagsToComments($trackInfo);

               // put the relevant comments_html array data into a simpler array called $trkFile, which we'll use throughout the program 
               $trkFile[$i]['title'] = (isset($trackInfo['comments_html']['title'][0]) ? $trackInfo['comments_html']['title'][0] : "");
               $trkFile[$i]['artist'] = (isset($trackInfo['comments_html']['artist'][0]) ? $trackInfo['comments_html']['artist'][0] : "");
               $bitrate = explode(".",($trackInfo['audio']['bitrate']/1000));
               $trkFile[$i]['bitrate'] = $bitrate[0]."k";
               $trkFile[$i]['playtime'] = $trackInfo['playtime_string'];
               $trkFile[$i]['genre'] = (isset($trackInfo['comments_html']['genre'][0]) ? $trackInfo['comments_html']['genre'][0] : "");
               if ($ext == 'ogg' || $ext == 'flac' || $ext == 'm4a') {
                  $trkFile[$i]['num'] = (isset($trackInfo['comments_html']['tracknumber'][0]) ? $trackInfo['comments_html']['tracknumber'][0] : "");
               } else {
                  $trkFile[$i]['num'] = (isset($trackInfo['comments_html']['track'][0]) ? $trackInfo['comments_html']['track'][0] : "");
               }
               $trkFile[$i]['album'] = (isset($trackInfo['comments_html']['album'][0]) ? $trackInfo['comments_html']['album'][0] : "");
               $trkFile[$i]['filepath'] = (isset($trackInfo['filepath']) ? $trackInfo['filepath'] : "");
               $trkFile[$i]['filename'] = (isset($trackInfo['filename']) ? $trackInfo['filename'] : "");
               $trkFile[$i]['ext'] = $ext;
	       $trkFile[$i]['filesize'] = filesize($incomingDir.$file);


               
//               echo ($incomingDir.$file . ': ' . $trkFile[$i]['artist'] . ', ' . $trkFile[$i]['title'] . ' (' . $trkFile[$i]['album'] . ')<br />');
               
               //check if this track is already in the database...
               //first, is there a track in the database with the same track number and title? 
               
               if ($trkExists) unset($trkExists);
               
               //make sure there's actually metadata... if not, we'll just have to cancel the whole sha-bang. 
               //if (!$trkFile[$i]['title'] || !$trkFile[$i]['artist'] || !$trkFile[$i]['album']) break; // this is a stupid way of going about it, though.
               
                 $fileMatchAlbStatement = "SELECT * 
					   FROM `album` 
                                           WHERE (LOWER(`title`) LIKE '%".mysql_real_escape_string(strtolower($trkFile[$i]['album']))."%') 
                                           AND (
                                           (LOWER(`artist`) LIKE '%".mysql_real_escape_string(strtolower($trkFile[$i]['artist']))."%') 
                                           OR  (LOWER(`artist`) LIKE '%various%')) 
                                           LIMIT 1 ";
                  $fileMatchAlbQuery = mysql_query($fileMatchAlbStatement);

                  //for every matching album (album with same title and artist)
                  while ($fileMatchAlb = mysql_fetch_array($fileMatchAlbQuery)) {
                     $fileMatchTrkStatement = "SELECT * FROM `track` 
                                               WHERE (LOWER(`title`) 
					       LIKE '%".mysql_real_escape_string(strtolower($trkFile[$i]['title']))."%')";

                     //this statement will check if the song title is already in the album 
                     if ($trkFile[$i]['num']) $fileMatchTrkStatement .= " AND (`trackno`='".$trkFile[$i]['num']."') ";
                     $fileMatchTrkQuery = mysql_query($fileMatchTrkStatement);
                  
                     //execute the following for every song match: 
                     while ($fileMatchTrk = mysql_fetch_array($fileMatchTrkQuery)) {
                        $trkExists = true;
                        if (!$fileMatchTrk['filename'] || !$fileMatchTrk['filepath'] || !is_file($fileMatchTrk['filepath'].$fileMatchTrk['filename'])) {
                           //echo('there is no file associated with this track, but the album exists.<br />');
                           $addTrkToAlb[$j] = $trkFile[$i];
                           $addTrkToAlb[$j]['cdid'] = $fileMatchTrk['cddbid'];
                           //echo($addTrkToAlb[$j]['filepath']);
                           //$addTrkToAlb[$j]['filepathname'] = $trkFile[$i]['filepath'] . $trkFile['filename'];
                           $j++;
                        } else {
                           //echo('this file already exists in the DB<br />');
                           $trkFilePresent[$k] = $trkFile[$i];
                           $trkFilePresent[$k]['oldFile'] = $fileMatchTrk['filepath'].$fileMatchTrk['filename'];
                           $trkFilePresent[$k]['trackId'] = $fileMatchTrk['id'];
                           ?><pre><?php
                           var_dump($trkFilePresent[$k]);
                           ?></pre><?php
                           $k++;
                        } // ends matching track with file in-place
                     } // end fileMatchTrk 
                  }  // end fileMatchAlb

                  if (!$trkExists) {
                     //echo('this track aint in the DB at all.<br />');
                     
                     //the following is for adding Albums files to the DB from scratch and moving files to the UNSORTED directory
                     $addTrkAndAlb[++$l] = $trkFile[$i];
                  }
		  
		  // bump that iterator up!
                  $i++;

/*                  $query = "INSERT INTO `mp3` (
                  title,
                  artist,
                  bitrate,
                  playtime,
                  genre,
                  track,
                  album,
                  filename,
                  filepath,
                  dateentered,
                  filesize
                  ) values (
                  '".mysql_escape_string($title)."',
                  '".mysql_escape_string($artist)."',
                  '".mysql_escape_string($bitrate)."',
                  '".mysql_escape_string($playtime)."',
                  '".mysql_escape_string($genre)."',
                  '".mysql_escape_string($track)."',
                  '".mysql_escape_string($album)."',
                  '".mysql_escape_string($trackInfo['filename'])."',
                  '".mysql_escape_string($trackInfo['filepath'])."',
                  now(),
                  '$size')";
                  mysql_query($query) or die(mysql_error()); 
                  */
                }
            }
            // if item is a directory re-run the function to deep scan and grab lower level files...burrito
            else if(is_dir($incomingDir.$file)) {
               if($file != "." && $file != "..") {
                    $subDir = $incomingDir.$file;
                    loadTrkFileInfo($subDir."/");
               }
            }
         }
         closedir($handle);
      }
      $loadTrkFileInfo[addTrkAndAlb] = $addTrkAndAlb;
      $loadTrkFileInfo[TrkDbExists] = $addTrkToAlb;
      return $loadTrkFileInfo;
}


// sortAndGroup () function 
// This function sorts all of the scanned files from an array and appends a 
// cd disc ID or new ID when it thinks it has found an album 
// 
// accepts: 
// 1. an array with all tracks and their metadata
// 
// returns:
// 1. the same array, plus a "cdid" field, which may contain "n1", "n2", "n3", etc. values for new discs. 

function sortAndGroup ($fileInfoArray) {
   $alb['album'] = array();
   $i = 0;
   foreach ($fileInfoArray as $trk) {
//   var_dump($trk);
      foreach ($trk as $trk) {
         var_dump($trk['album']);
//         echo('<br />compare to:<br />');
//         var_dump($alb['album']);
//         echo('<br />');
         if (!in_array(strtolower($trk['album']), $alb['album'])) {
//            echo ($trk['album'].'is not in the array!<br />');
            $alb['album'][$i] = strtolower($trk['album']);
            $alb['albId'][$i] = 'n'.$i;
            $i++;
         } elseif ($trk[artist] && $trk[album]) {
            // if we've gotten here, we need to check for a match for our CD in the database
            $fileMatchAlbStatement = "SELECT * 
					   FROM `album` 
                  WHERE (LOWER(`title`) LIKE '%".mysql_real_escape_string(strtolower($trk['album']))."%') 
                  AND (
                  (LOWER(`artist`) LIKE '%".mysql_real_escape_string(strtolower($trk['artist']))."%') 
                  OR  (LOWER(`artist`) LIKE '%various%')) 
                  ORDER BY `add_date` DESC ";
                  $fileMatchAlbQuery = mysql_query($fileMatchAlbStatement);
                  while ($fileMatchAlb = mysql_fetch_array($fileMatchAlbQuery)) {
                     echo('<h1>'.$fileMatchAlb[artist].'/'.$fileMatchAlb[tracks].'!</h1>');
                  }
                  $alb['albId'] = fileMatchAlb[artist];
//            echo('no match!');
//            var_dump($alb);
         }
      }
   }

   ?><pre><?php
      var_dump ($alb);
      ?></pre><?php
//   }
//   var_dump ($fileInfoArray);
}


// sanitizeAndMove() function
//
// Description: 
// This function moves files from the "incoming" directory to the outgoing directory,
// changing names and creating folders as appropriate (to have a consistent naming system)
// 
// inputs:
// 1. the existing file name
// 2. an array with file information/metadata
// 3. destination directory 
//
// Outputs:
// 1. returns 'true' if the actions are completed; otherwise false (or is it null?) 
// 
function sanitizeAndMove ($oldFile, $fileInfo, $outgoingDir = '/var/music/UNSORTED/') {   
   
   //set umask properly so that chmodding works properly in all configurations
   $old_umask = umask(0);
   
   //sanitize album, artist, and title
   $artist = str_replace('/', '-', $fileInfo['artist']);
   $album = str_replace('/', '-', $fileInfo['album']);
   $title = $fileInfo['num'] . ' - ' .str_replace('/', '-', $fileInfo['title']) . '.' . $fileInfo['ext'];
   
   //check if directory exists, if not, add it
   if (!is_file($outgoingDir.$artist.'/'.$album.'/'.$title)) {
      if (!is_dir($outgoingDir.$artist.'/'.$album)) {
         if (!is_dir($outgoingDir.$artist)) mkdir($outgoingDir.$artist, 0777);
         mkdir($outgoingDir.$artist.'/'.$album . '/', 0777);
      }
   }
   //format the title to make it work for a filename 
   $newFilename = $outgoingDir.$artist.'/'.$album.'/'.$title;
   if (rename($oldFile, $newFilename)) $success = true;
   else $success = false;
   
   //set umask back to what it was just in case.
   umask($old_umask);
   
   return $success;
}


// this function takes the incoming track metadata as well as info in the
// $massInfo array, which the user can set at fileScan time to make manual metadata entry easier.
function addToDb ($trk, $massInfo = NULL) { 
   // if an incoming cddbid exists, then add all the albums to that; if not, make a new one
   if ($trk['cdid']) {
      //insert into existing album
      
   } else {
      // create a new album and insert the track into it.
      $createAlbQuery = mysql_query("
         INSERT INTO `album`
         SET 
         `title`='".$trk['album']."',
         `artist`='".$trk['artist']."',
         `tracks`='1'
         ");
   }
   // we should probably return the cddbid somehow
}






// end functions, begin the page. 

if ($do == 'importFiles') {
   echo('we would have just done all the importing...<br />');
   if ($_POST['trkAppend']){
      foreach ($_POST['trkAppend'] as $trk) {
         echo($trk['artist'] . ' - ' . $trk['num'] . '. ' . $trk['title'] . ' [' . $trk['album'] . ']' . '<br />');
         if ($trk['execute'] == 'true') {
            sanitizeAndMove ($trk['filepathname'], $trk);
	    addToDb ($trk);
         }
      }
   }
   echo("<br /><h3>These were added anew!</h3>");
   if ($_POST['trkAdd']) {
      foreach ($_POST['trkAdd'] as $trk) {
//         if ($trk['execute'] == 'true') {
            sanitizeAndMove ($trk['filepathname'], $trk);
            addToDb ($trk);
            echo('' . $trk['title'] . '<br />');
//         }
      }
   }
} else if ($do == 'scanFiles') {
   $file = loadTrkFileInfo();
   $file = sortAndGroup($file);
   $addTrkAndAlb = $file[addTrkAndAlb];
         ?>
      <form method="post">
      <?php
   $i = 0; // iterator
   if ($addTrkToAlb) {
      echo ('<h3>these tracks will be added to existing albums</h3>');
         foreach ($addTrkToAlb as $trk) {
            echo (
	    '<input type="checkbox" checked="checked" name="trkAppend['.$i.'][execute]" value="true" /><input type="hidden" name="trkAppend[' . $i . '][title]" value="' . $trk['title'] .
	    '" /><input type="hidden" name="trkAppend[' . $i . '][album]" value="' . $trk['album'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][num]" value="' . $trk['num'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][artist]" value="' . $trk['artist'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][playtime]" value="' . $trk['playtime'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][genre]" value="' . $trk['genre'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][bitrate]" value="' . $trk['bitrate'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][ext]" value="' . $trk['ext'] . 
	    '" /><input type="hidden" name="trkAppend[' . $i . '][filepathname]" value="' . $trk['filepath'] . '/' . $trk['filename'] . 
	    '" />'
	    . $trk['title'] . '<br />' ."\n");
	    $i++;
         }
      }
      $i = 0; // iterator
      if ($addTrkAndAlb) {
         echo ('<h3>these tracks and albums will be added to the DB</h3>');
         foreach ($addTrkAndAlb as $trk) {
            echo ('<input type="hidden" name="trkAdd[' . $i++ . '][title]" value="' . $trk['title'] . '" />' . $trk['title'] . '<br />' . "\n");
         }
      }
      $i = 0;
      if ($trkPresent) {
         echo ('<h3>these tracks are already in the DB with files</h3>');
         foreach ($trkPresent as $trkReplace) {
	         echo ($trkReplace['title'] . '<br />');
         }
      }
   ?>
      <input type="hidden" name="do" value="importFiles" />
      <input type="submit" value="Import into DB!" />
      </form>
      <?php
} else {
?>
<form method="post">
Enter Folder:<br>
(use forward slashes and make sure you have a trailing slash on the end ex: c:/path/to/files/ )<br>
<input type="text" name="rootDir"><br>
<input type="submit" value="Scan New Music Files!">
<input type="hidden" name="do" value="scanFiles" /></form>
<?php
}
   ?></pre><?
?> 
